package it.itsvil.ejb.session;

import it.itsvil.bean.user.UserBean;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class RequestBean implements SessionBean, RequestRemoteBusiness {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private SessionContext context;

	/**
	 * Gets JDBC connection from the connection pool.
	 * 
	 * @return The JDBC connection
	 */
	private Connection getConnection() throws Exception {
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:/DefaultDS1");
			System.out.println("DS:" + ds);
			// ctx.close();
			return ds.getConnection();
		} catch (Exception e) {
			System.err.println("Couldn't get datasource!");
			e.printStackTrace();
			throw e;
		}
	}

	public void setSessionContext(SessionContext aContext) {
		System.out.println("setSessionContext() called.");
		context = aContext;
	}

	/**
	 * @see SessionBean#ejbActivate()
	 */
	public void ejbActivate() {
		System.out.println("ejbActivate() called.");
	}

	/**
	 * @see SessionBean#ejbPassivate()
	 */
	public void ejbPassivate() {
		System.out.println("ejbPassivate() called.");
	}

	/**
	 * @see SessionBean#ejbRemove()
	 */
	public void ejbRemove() {
		System.out.println("ejbRemove() called.");
	}

	public void ejbCreate() {
		System.out.println("ejbCreate() called.");
	}

	public UserBean isLogged(UserBean userBean) throws RemoteException {
		UserBean current = null;
		String email = userBean.getEmail();
		String password = userBean.getPassword();

		PreparedStatement pstmt = null;
		Connection conn = null;
		try {
			/*
			 * 1) Acquire a new DB Connection
			 */
			conn = getConnection();
			/*
			 * 2) Get account from the DB, querying
			 * 
			 * by account ID
			 */
			pstmt = conn.prepareStatement("select * from users "
					+ "where email = ? AND password = ?");
			pstmt.setString(1, email);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				current = new UserBean();
				current.setName(rs.getString("name"));
				current.setSurname(rs.getString("surname"));
				current.setEmail(rs.getString("email"));
				current.setPassword(rs.getString("password"));
			}
		} catch (Exception ex) {
			throw new EJBException("User " + email + " not found", ex);
		} finally {
			/*
			 * 3) Release the DB Connection
			 */
			try {
				if (pstmt != null)
					pstmt.close();
			} catch (Exception e) {
			}
			try {
				if (conn != null)
					conn.close();
			} catch (Exception e) {
			}
		}
		return current;
	}
}
